<template>
  <div class="my-posts-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <div class="navbar-left">
          <router-link to="/home" class="back-btn">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
            返回首页
          </router-link>
        </div>
        <div class="navbar-center">
          <h1>我的帖子</h1>
        </div>
        <div class="navbar-right">
          <router-link to="/discussion" class="publish-btn">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
              <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
            </svg>
            发布新帖
          </router-link>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card">
        <div class="stat-icon">📝</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.totalPosts }}</div>
          <div class="stat-label">发帖数量</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">👀</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.totalViews }}</div>
          <div class="stat-label">总浏览量</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">❤️</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.totalLikes }}</div>
          <div class="stat-label">总点赞数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">💬</div>
        <div class="stat-info">
          <div class="stat-value">{{ stats.totalComments }}</div>
          <div class="stat-label">总评论数</div>
        </div>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="content-container">
      <div v-if="loading" class="loading">
        <svg viewBox="0 0 24 24" width="40" height="40" fill="currentColor" class="spin">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6h2c0-2.21 1.79-4 4-4V6z"/>
        </svg>
        <p>加载中...</p>
      </div>

      <div v-else-if="posts.length === 0" class="empty">
        <svg viewBox="0 0 24 24" width="64" height="64" fill="currentColor" opacity="0.3">
          <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
        </svg>
        <p>还没有发布过帖子</p>
        <router-link to="/discussion" class="empty-btn">去发帖</router-link>
      </div>

      <div v-else class="posts-list">
        <div 
          v-for="post in displayPosts" 
          :key="post.id"
          class="post-item"
          @click="goToPost(post.id)"
        >
          <div class="post-header">
            <div class="post-tags">
              <span 
                v-for="tag in post.tags" 
                :key="tag"
                class="post-tag"
              >
                {{ tag }}
              </span>
            </div>
            <div class="post-actions">
              <button class="action-btn" @click.stop="editPost(post)">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                </svg>
                编辑
              </button>
              <button class="action-btn delete" @click.stop="deletePost(post)">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                </svg>
                删除
              </button>
            </div>
          </div>
          
          <div class="post-title">{{ post.title }}</div>
          <div class="post-content">{{ post.content }}</div>
          
          <div class="post-footer">
            <div class="post-stats">
              <span class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/>
                </svg>
                {{ post.views }}
              </span>
              <span class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
                </svg>
                {{ post.likes }}
              </span>
              <span class="stat-item">
                <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                  <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
                </svg>
                {{ post.comments }}
              </span>
            </div>
            <div class="post-time">{{ formatTime(post.createTime) }}</div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="posts.length > 0" class="pagination">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1"
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button 
          class="page-btn"
          :disabled="currentPage === totalPages"
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getMyPosts, getPostsStats, deleteDiscussion, uploadAvatar } from '../api/user'
import { getAvatarUrl } from '../utils/url'
import Toast from '../components/Toast.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const currentPage = ref(1)
const pageSize = 10

const posts = ref([])
const stats = ref({
  totalPosts: 0,
  totalViews: 0,
  totalLikes: 0,
  totalComments: 0
})

const displayPosts = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return posts.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(posts.value.length / pageSize) || 1
})

onMounted(() => {
  loadPostsData()
})

async function loadPostsData() {
  loading.value = true
  try {
    // 加载统计数据
    const statsRes = await getPostsStats()
    if (statsRes.code === 200) {
      stats.value = statsRes.data
    }
    
    // 加载帖子列表
    const postsRes = await getMyPosts()
    if (postsRes.code === 200) {
      posts.value = postsRes.data.list || []
    }
  } catch (error) {
    console.error('加载帖子数据失败:', error)
  } finally {
    loading.value = false
  }
}

function changePage(page) {
  currentPage.value = page
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

function goToPost(postId) {
  router.push(`/discussion/${postId}`)
}

function editPost(post) {
  // TODO: 实现编辑功能
  console.log('编辑帖子:', post)
  alert('编辑功能即将上线')
}

async function deletePost(post) {
  if (!confirm('确定要删除这篇帖子吗？')) {
    return
  }
  
  try {
    const res = await deleteDiscussion(post.id)
    if (res.code === 200) {
      alert('删除成功')
      loadPostsData()
    }
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败，请重试')
  }
}

function formatTime(timeStr) {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time

  if (diff < 3600000) {
    return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
    return Math.floor(diff / 3600000) + '小时前'
  } else if (diff < 604800000) {
    return Math.floor(diff / 86400000) + '天前'
  } else {
    return time.toLocaleDateString()
  }
}
</script>

<style scoped lang="scss">
.my-posts-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.top-navbar {
  background: white;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .navbar-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .navbar-left {
    .back-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      background: #f5f5f5;
      border-radius: 8px;
      text-decoration: none;
      color: #333;
      font-size: 14px;
      transition: all 0.3s;
      
      &:hover {
        background: #e8e8e8;
      }
    }
  }
  
  .navbar-center {
    h1 {
      font-size: 20px;
      font-weight: 600;
      color: #333;
      margin: 0;
    }
  }
  
  .navbar-right {
    .publish-btn {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px;
      text-decoration: none;
      font-size: 14px;
      font-weight: 500;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
    }
  }
}

.stats-container {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 24px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  
  .stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }
    
    .stat-icon {
      font-size: 36px;
      width: 60px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f5f7fa;
      border-radius: 12px;
    }
    
    .stat-info {
      flex: 1;
      
      .stat-value {
        font-size: 28px;
        font-weight: 700;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #999;
      }
    }
  }
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px 40px;
  
  .loading, .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: #999;
    
    svg {
      margin-bottom: 16px;
      
      &.spin {
        animation: spin 1s linear infinite;
        color: #667eea;
      }
    }
    
    p {
      font-size: 16px;
      margin-bottom: 20px;
    }
    
    .empty-btn {
      padding: 12px 32px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px;
      text-decoration: none;
      font-size: 15px;
      font-weight: 500;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
      }
    }
  }
  
  .posts-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
    
    .post-item {
      background: white;
      border-radius: 12px;
      padding: 24px;
      cursor: pointer;
      transition: all 0.3s;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
      }
      
      .post-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
        
        .post-tags {
          display: flex;
          gap: 8px;
          
          .post-tag {
            padding: 4px 12px;
            background: #f0f2f5;
            border-radius: 12px;
            font-size: 12px;
            color: #666;
          }
        }
        
        .post-actions {
          display: flex;
          gap: 8px;
          
          .action-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            padding: 6px 12px;
            background: #f5f5f5;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            color: #666;
            cursor: pointer;
            transition: all 0.3s;
            
            &:hover {
              background: #667eea;
              color: white;
            }
            
            &.delete:hover {
              background: #f44336;
              color: white;
            }
          }
        }
      }
      
      .post-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 12px;
        line-height: 1.5;
      }
      
      .post-content {
        font-size: 14px;
        color: #666;
        line-height: 1.8;
        margin-bottom: 16px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .post-footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 16px;
        border-top: 1px solid #f0f2f5;
        
        .post-stats {
          display: flex;
          gap: 20px;
          
          .stat-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            color: #999;
            
            svg {
              opacity: 0.6;
            }
          }
        }
        
        .post-time {
          font-size: 13px;
          color: #999;
        }
      }
    }
  }
  
  .pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;
    margin-top: 32px;
    
    .page-btn {
      padding: 10px 24px;
      background: white;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      cursor: pointer;
      font-size: 14px;
      color: #333;
      transition: all 0.3s;
      
      &:hover:not(:disabled) {
        background: #667eea;
        color: white;
        border-color: #667eea;
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
    
    .page-info {
      font-size: 14px;
      color: #666;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

